package _01_动态数组;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class _414_第三大的数 {

    public static void main(String[] args) {
        _414_第三大的数 v = new _414_第三大的数();
        int[] ins = new int[]{1, 2, -2147483648};
        System.out.println(v.thirdMax(ins));

    }

    // 利用遍历保存元素
    public int thirdMax(int[] nums) {
        long a = Long.MIN_VALUE, b = Long.MIN_VALUE, c = Long.MIN_VALUE;
        for (long num : nums) {
            if (num > a) {
                c = b;
                b = a;
                a = num;
            } else if (a > num && num > b) {
                c = b;
                b = num;
            } else if (b > num && num > c) {
                c = num;
            }
        }
        return c == Long.MIN_VALUE? (int)a: (int)c;
    }

    // 引用TreeSet保存源
    public int thirdMax1(int[] nums) {
        TreeSet<Integer> set = new TreeSet<>(Comparator.reverseOrder());
        for (Integer integer : nums) {
            set.add(integer);
            if (set.size() > 3) {
                set.pollLast();
            }
        }
        return set.size() == 3? set.last(): set.first();
    }

}
